<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchForm"
      :inline="true"
      label-width="80px"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>
    
    <!-- 统计卡片 -->
    <div class="stats-container">
      <StatCard
        title="用户总数"
        :value="statistics.totalUsers || 0"
        icon="User"
        type="primary"
        :trend="statistics.userGrowth"
      />
      <StatCard
        title="今日新增"
        :value="statistics.todayNewUsers || 0"
        icon="UserFilled"
        type="success"
      />
      <StatCard
        title="活跃用户"
        :value="statistics.activeUsers || 0"
        icon="UserFilled"
        type="warning"
      />
      <StatCard
        title="会员用户"
        :value="statistics.vipUsers || 0"
        icon="Crown"
        type="danger"
      />
    </div>
    
    <!-- 用户表格 -->
    <Card title="用户列表">
      <template #extra>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </template>
      
      <CommonTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </template>
        
        <template #vip="{ row }">
          <el-tag v-if="row.isVip" type="warning">会员</el-tag>
          <span v-else>-</span>
        </template>
        
        <template #action="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleToggleStatus(row)"
          >
            <el-icon><Switch /></el-icon>
            {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </CommonTable>
    </Card>
    
    <!-- 用户表单对话框 -->
    <CommonDialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="600px"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password 
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="ACTIVE">启用</el-radio>
            <el-radio label="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-checkbox-group v-model="formData.roles">
            <el-checkbox label="ADMIN">管理员</el-checkbox>
            <el-checkbox label="USER">普通用户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            placeholder="请输入备注" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
    </CommonDialog>
    
    <!-- 用户详情对话框 -->
    <CommonDialog
      v-model="detailVisible"
      title="用户详情"
      width="800px"
      :show-footer="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">{{ detailData.username }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ detailData.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ detailData.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="会员状态">
          <el-tag v-if="detailData.isVip" type="warning">会员</el-tag>
          <span v-else>普通用户</span>
        </el-descriptions-item>
        <el-descriptions-item label="会员到期时间">
          {{ detailData.vipExpireTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="角色" :span="2">
          <el-tag v-for="role in detailData.roles" :key="role" style="margin-right: 5px;">
            {{ role === 'ADMIN' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ detailData.remark || '-' }}
        </el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-tabs">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="配额信息" name="quota">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="总配额">{{ detailData.quota?.totalQuota || 0 }}</el-descriptions-item>
              <el-descriptions-item label="已使用配额">{{ detailData.quota?.usedQuota || 0 }}</el-descriptions-item>
              <el-descriptions-item label="剩余配额">{{ detailData.quota?.remainingQuota || 0 }}</el-descriptions-item>
              <el-descriptions-item label="配额使用率">
                <el-progress 
                  :percentage="detailData.quota?.usageRate || 0" 
                  :color="getQuotaColor(detailData.quota?.usageRate || 0)"
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="会员信息" name="member">
            <el-descriptions v-if="detailData.isVip" :column="2" border>
              <el-descriptions-item label="会员等级">{{ detailData.memberLevel?.name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="会员开始时间">{{ detailData.memberLevel?.startTime || '-' }}</el-descriptions-item>
              <el-descriptions-item label="会员到期时间">{{ detailData.memberLevel?.endTime || '-' }}</el-descriptions-item>
              <el-descriptions-item label="会员状态">
                <el-tag type="success">有效</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            <el-empty v-else description="该用户不是会员" />
          </el-tab-pane>
          <el-tab-pane label="操作记录" name="logs">
            <CommonTable
              :data="detailData.logs || []"
              :columns="logColumns"
              :show-pagination="false"
              :max-height="300"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, getUserDetail, createUser, updateUser, deleteUser, batchDeleteUsers, updateUserStatus, getUserStatistics } from '@/api/user'
import { useTable } from '@/hooks/useTable'
import { useForm } from '@/hooks/useForm'
import { useDialog } from '@/hooks/useDialog'
import { formatDate, formatNumber } from '@/utils'

// 表格列配置
const columns = [
  {
    type: 'selection',
    width: '55'
  },
  {
    prop: 'id',
    label: 'ID',
    width: '80'
  },
  {
    prop: 'username',
    label: '用户名',
    minWidth: '120'
  },
  {
    prop: 'email',
    label: '邮箱',
    minWidth: '180'
  },
  {
    prop: 'phone',
    label: '手机号',
    minWidth: '120'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    slot: 'status'
  },
  {
    prop: 'isVip',
    label: '会员',
    width: '100',
    slot: 'vip'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'action',
    label: '操作',
    width: '250',
    slot: 'action',
    fixed: 'right'
  }
]

// 操作记录列配置
const logColumns = [
  {
    prop: 'operation',
    label: '操作',
    width: '120'
  },
  {
    prop: 'operator',
    label: '操作人',
    width: '120'
  },
  {
    prop: 'operateTime',
    label: '操作时间',
    width: '180'
  },
  {
    prop: 'remark',
    label: '备注'
  }
]

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  totalUsers: 0,
  todayNewUsers: 0,
  activeUsers: 0,
  vipUsers: 0,
  userGrowth: 0
})

// 表格相关
const {
  tableData,
  loading,
  pagination,
  selectedRows,
  loadData,
  handleSelectionChange,
  handleSortChange,
  handleSizeChange,
  handleCurrentChange
} = useTable(getUserList, {
  defaultParams: searchForm,
  immediate: false
})

// 表单相关
const defaultFormData = {
  username: '',
  email: '',
  password: '',
  phone: '',
  status: 'ACTIVE',
  roles: ['USER'],
  remark: ''
}

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const {
  formData,
  formRef,
  submitting,
  resetForm,
  validateForm,
  submitForm
} = useForm(defaultFormData, handleSubmit, {
  resetAfterSubmit: false
})

// 对话框相关
const {
  visible: dialogVisible,
  showDialog,
  hideDialog
} = useDialog()

const {
  visible: detailVisible,
  showDialog: showDetailDialog,
  hideDialog: hideDetailDialog
} = useDialog()

// 其他变量
const tableRef = ref(null)
const dialogType = ref('add')
const detailData = reactive({})
const activeTab = ref('quota')

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const response = await getUserStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 处理搜索
const handleSearch = () => {
  loadData({
    ...searchForm,
    startTime: searchForm.dateRange?.[0],
    endTime: searchForm.dateRange?.[1]
  })
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  showDialog()
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const response = await getUserDetail(row.id)
    if (response) {
      dialogType.value = 'edit'
      Object.assign(formData, {
        ...response,
        password: '' // 编辑时不显示密码
      })
      showDialog()
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
  }
}

// 处理查看
const handleView = async (row) => {
  try {
    const response = await getUserDetail(row.id)
    if (response) {
      Object.assign(detailData, response)
      activeTab.value = 'quota'
      showDetailDialog()
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.username}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 个用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeleteUsers(ids)
      ElMessage.success('批量删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('批量删除失败', error)
    }
  }).catch(() => {})
}

// 处理切换状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
  const statusText = newStatus === 'ACTIVE' ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${statusText}用户 "${row.username}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateUserStatus(row.id, newStatus)
      ElMessage.success(`${statusText}成功`)
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error(`${statusText}失败`, error)
    }
  }).catch(() => {})
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 处理表单提交
async function handleSubmit() {
  try {
    if (dialogType.value === 'add') {
      await createUser(formData)
      ElMessage.success('新增成功')
    } else {
      await updateUser(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    hideDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 处理取消
const handleCancel = () => {
  hideDialog()
}

// 获取配额颜色
const getQuotaColor = (percentage) => {
  if (percentage < 30) return '#67c23a'
  if (percentage < 70) return '#e6a23c'
  return '#f56c6c'
}

onMounted(() => {
  loadData()
  getStatisticsData()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .detail-tabs {
    margin-top: 20px;
  }
}
</style>